package com.nextgen.controllers;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import com.nextgen.bean.SellersCategory;
import com.nextgen.helper.NextgenConstants;
import com.nextgen.services.SellerService;


/**
 * SellerController class will expose a series of RESTful end points
 */
@Controller
public class SellerController {

	@Autowired
	private SellerService sellerService;

	@Autowired
	private View jsonView_i;

	private static final Logger logger_c = Logger.getLogger(AsinController.class);

	/**
	 * Gets a asin by asin id.
	 *
	 * @param asinId_p
	 *            the asin id_p
	 * @return the asin
	 */
	@RequestMapping(value = "/rest/sellers/categories/{sellerId}", method = RequestMethod.GET)
	public ModelAndView getSellersCategories(@PathVariable("sellerId") String sellerId_p) {
		SellersCategory sellersCategory = null;

		/* validate seller Id parameter */
		if (isEmpty(sellerId_p) || sellerId_p.length() < 4) {
			String sMessage = "Error invoking getSellersCategories - Invalid seller Id parameter";
			return createErrorResponse(sMessage);
		}

		try {
			sellersCategory = sellerService.getCategoriesBySellerId(sellerId_p);
		} catch (Exception e) {
			String sMessage = "Error invoking getAsin. [%1$s]";
			return createErrorResponse(String.format(sMessage, e.toString()));
		}

		if(sellersCategory==null) {
			String sMessage = "Error - Seller with sellerId: " + sellerId_p+ " NOT found.";
			return createErrorResponse(sMessage);
		}
		logger_c.debug("Returing seller categories: " + sellersCategory.toString());
		return new ModelAndView(jsonView_i, NextgenConstants.DATA_FIELD, sellersCategory);
	}

	public static boolean isEmpty(String s_p) {
		return (null == s_p) || s_p.trim().length() == 0;
	}

	/**
	 * Create an error REST response.
	 *
	 * @param sMessage
	 *            the s message
	 * @return the model and view
	 */
	private ModelAndView createErrorResponse(String sMessage) {
		return new ModelAndView(jsonView_i, NextgenConstants.ERROR_FIELD, sMessage);
	}

	/**
	 * Injector methods.
	 *
	 * @param sellerService_p
	 *            the new seller service
	 */
	public void setsellerService(SellerService sellerService_p) {
		sellerService = sellerService_p;
	}

	/**
	 * Injector methods.
	 *
	 * @param view
	 *            the new json view
	 */
	public void setJsonView(View view) {
		jsonView_i = view;
	}

}
